package lumis.service.portalmanagement.group;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import lumis.doui.processaction.ProcessActionHandler;
import lumis.doui.source.Source;
import lumis.portal.PortalException;
import lumis.portal.group.GroupConfig;
import lumis.portal.group.databaseviewmembership.DatabaseViewGroupConfig;
import lumis.portal.manager.ManagerFactory;
import lumis.util.XmlUtil;

/**
 * Process action used in the database view membership group configuration.
 *
 * @version $Revision: 10458 $ $Date: 2009-06-02 15:49:09 -0300 (Tue, 02 Jun 2009) $
 * @since 4.2.1
 */
public class DatabaseViewGroupProcessActionHandler extends ProcessActionHandler<Source<?>>
{
	public void processAction() throws PortalException
	{
		String actionType = XmlUtil.readAttributeString("actionType", processActionNode);
		if ("configure".equals(actionType))
			processConfigure();
		else if ("validateFormula".equals(actionType))
			processValidateFormula();
		else if ("clearCache".equals(actionType))
			processClearCache();
		else
			throw new IllegalArgumentException("actionType: " + actionType);
		
		addDefaultResponse();
	}

	private void processClearCache() throws PortalException
	{
		String groupId = douiContext.getRequest().getParameter("groupId");
		GroupConfig groupConfig = ManagerFactory.getGroupManager().get(sessionConfig, groupId, transaction);
		String groupTypeId = groupConfig.getGroupTypeId();
		
		ManagerFactory.getGroupManager().invalidateGroupMembershipProvider(sessionConfig, groupTypeId, transaction);
	}
	
	private void processValidateFormula() throws PortalException
	{
		String groupConfigId = (String) douiContext.getRequest().getAttribute("groupConfigId");
		DatabaseViewGroupConfig groupConfig = ManagerFactory.getEntityManager().find(DatabaseViewGroupConfig.class, groupConfigId);
		try
		{
			groupConfig.getMembersFormula();
		}
		catch(IllegalStateException e)
		{
			throw new PortalException("STR_INVALID_FORMULA", getResource(), e);
		}
	}

	private void processConfigure()
	{
		String groupId = douiContext.getRequest().getParameter("groupId");
		
		// get groupConfig
		EntityManager entityManager = ManagerFactory.getEntityManager();
		DatabaseViewGroupConfig groupConfig;
		try
		{
			groupConfig = (DatabaseViewGroupConfig)entityManager.createNamedQuery(
					DatabaseViewGroupConfig.NAMED_QUERY_FIND_BY_GROUP_ID)
					.setParameter("groupId", groupId)
					.getSingleResult();
		}
		catch(NoResultException e)
		{
			groupConfig = new DatabaseViewGroupConfig();
			groupConfig.setGroupId(groupId);
			entityManager.persist(groupConfig);
			entityManager.flush();
		}

		// set groupConfigId in a attribute for next process action to use
		douiContext.getRequest().setAttribute("groupConfigId", groupConfig.getId());
	}
}
